<?php
namespace app\admin\controller;
use app\admin\model\AuthRule;
use cate_tree\CateTree;
use think\Session;
use think\Controller;
use think\Db;


class UserAuth extends Controller{
    /**
     * 构造函数
     * @author 王柯 <wangke.email@foxmail.com>
     * @return void
     */
    public function __construct(){
        parent::__construct();

        //检测Session是否存在
        $members = Session::get('book_user');

        if(empty($members['id'])){
            $this->redirect('login/index');
        }

        //验证用户权限
        $this->check_auth($members['id']);

        $this->assign('members',$members);
    }

    /**
     * 权限验证
     * @param int id 用户id *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return void
     */
    public function check_auth($id) {
        $Auth = new \auth\Auth();
        $user = Db::name('user')->where('id='.$id)->find();

        $name =  request()->controller().'/'.request()->action();
        $uid = $user['user_auth'];
        $type = request()->module();
        $mode = 'url';
        $relation = 'and';

//        if($Auth->check($name,$uid,$type,$mode,$relation)){
//            //权限id
//            $ids = explode(',',$Auth->getGroups($uid)[0]['rules']);
//
//            $where = [
//                'id' => ['in', $ids],
//                'type' => $type,
//                'status' => 1,
//            ];
//
//            //读取用户组所有权限规则
//            $rules = Db::name('auth_rule')->where($where)->field('name')->select();
//
//            $array = [];
//            foreach ($rules as $key => $val){
//                $array[$key] = strtolower($val['name']);
//            }
//
//            if(!in_array('index/index',$array)){
//                exit(alert('没有后台权限！',url('login/logout'),5,3));
//            }
//
//            //exit(alert('无访问权限！',url('index/index'),5,3));
//        }

    }

    /**
     * 权限管理
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function index(){
        return view("");
    }

    /**
     * 权限列表
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public function auth_list(){
        if(request()->isGet()) {
            $keywords = trim(input('get.keywords'));

            if(!empty($keywords)){
                $where = [
                    'name|title'
                    => ['like', "%{$keywords}%"]
                ];
            }else{
                $where = '';
            }

            $cate = (new CateTree());

            $cateResult = Db('auth_rule')->where($where)->select();

            $userAuth = $cate->create_tree($cateResult);

            $count = Db::name('auth_rule')->where($where)->count();

            $this->assign([
                'userAuth' => $userAuth ,
                'count' => $count ,
            ]);
        }

        return $this->fetch('user_auth');
    }

    /**
     * 新增权限
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed|\think\response\Json
     */
    public function add_auth(){

        /*$ruleTree = Db::name('auth_rule')
            ->field("*,concat(path,id) as paths")
            //->where('level !=3')
            ->order('paths desc')
            ->select();*/

        $cate = (new CateTree());

        $cateResult = Db('auth_rule')->select();

        $ruleTree = $cate->create_tree($cateResult);

        if(request()->isAjax()){
            $data = $_GET;
            //验证
            $validate = validate('auth_rule');
            if(!$validate->check($data)){
                return show(config('code.error'),$validate->getError());
            }

            if(isset($data['type'])){
                $data['type'] = strtolower($data['type']);
            }

            $auth = new AuthRule();
            if($data['pid'] != 0){
                $path = Db::name('auth_rule')->where('id='.$data['pid'])->field('id,path')->find();

                $data['path'] = $path['path'];
                $data['level'] = substr_count($path['path'],',');
                $re = $auth->save($data);

                if($re){
                    $path['id'] = $auth->getLastInsID();
                    $path['path'] = $data['path'].','.$path['id'];
                    $path['level'] = substr_count($path['path'],',');
                    $res = $auth->save($path);

                    if($res){
                        return show(config('code.success'), '新增权限成功！');
                    }else{
                        return show(config('code.error'), '新增权限失败！');
                    }
                }
            }elseif($data['pid'] == 0){
                $data['path'] = $data['pid'];
                $data['level'] = 1;
                $re = $auth->save($data);

                if($re){
                    $path['id'] = $auth->getLastInsID();
                    $path['path'] = $data['path'].','.$path['id'];
                    $res = $auth->save($path);

                    if($res){
                        return show(config('code.success'), '新增权限成功！');
                    }else{
                        return show(config('code.error'), '新增权限失败！');
                    }
                }
            }
        }

        $this->assign('ruleTree',$ruleTree);

        return $this->fetch('add_auth');
    }

    /**
     * 修改权限
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|mixed|string|\think\response\Json
     */
    public function edit_auth($id){
        $auths = Db('authRule')->where('id='.$id)->find();

        //查询子集权限
        $result = Db('authRule')->where('pid='.$id)->find();

        /*$ruleTree = Db::name('auth_rule')
            ->field("*,concat(path,id) as paths")
            ->where('level !=3')
            ->order('paths desc')
            ->select();*/

        $cate = (new CateTree());

        $cateResult = Db('auth_rule')->select();

        $ruleTree = $cate->create_tree($cateResult);

        if(request()->isAjax()){
            $data = $_GET;
            //验证
            $validate = validate('auth_rule');
            if(!$validate->check($data)){
                return show(config('code.error'),$validate->getError());
            }

            if(isset($data['type'])){
                $data['type'] = strtolower($data['type']);
            }

            $auth = new AuthRule();
            if($data['pid'] == 0){
                //判断修改顶级权限到其他目录权限下当前权限是否有子集权限
                if(($data['pid'] != $auths['pid']) && !empty($result)){
                    return show(config('code.error'),'该目录下还有子集权限不能添加到其他权限目录！');
                }

                $data['path'] = $data['pid'].','.$data['id'];
                $data['level'] = 1;
                $res = $auth->where('id='.$data['id'])->update($data);

                if($res){
                    return show(config('code.success'), '修改权限成功！');
                }else{
                    return show(config('code.error'), '修改权限失败！');
                }
            }else{
                //判断修改顶级权限到其他目录权限下当前权限是否有子集权限
                if(($data['pid'] != $auths['pid']) && !empty($result)){
                    return show(config('code.error'),'该目录下还有子集权限不能添加到其他权限目录！');
                }

                $path = Db::name('auth_rule')->where('id='.$data['pid'])->field('path,level')->find();
                $data['path'] = $path['path'] . ',' . $data['id'];
                $data['level'] = $path['level'] + 1;
                $res = $auth
                    ->where('id='.$data['id'])
                    ->update($data);
                if($res){
                    return show(config('code.success'), '修改权限成功！');
                }else{
                    return show(config('code.error'), '修改权限失败！');
                }
            }
        }

        $this->assign([
            'ruleTree'=>$ruleTree,
            'auths'=>$auths,
        ]);

        return $this->fetch('edit_auth');
    }

    /**
     * 删除权限
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|string|\think\response\Json
     */
    public function del_auth(){
        if(request()->isAjax()){
            $auth = new AuthRule();

            $data = Db::name('auth_rule')->where('pid='.$_GET['id'])->find();

            if(empty($data)){
                $result = $auth->where('id='.$_GET['id'])->delete();

                if($result){
                    return show(config('code.success'), '删除成功！');
                }else{
                    return show(config('code.error'), '删除失败！');
                }
            }else{
                return show(config('code.error'), '该规则下还有子集规则不能删除！');
            }
        }else{
            return show(config('code.error'), '非法请求！');
        }
    }
}